package com.oocl.euc.core.maintenance.service;

import com.oocl.euc.core.maintenance.model.Team;
import com.oocl.euc.core.maintenance.model.TeamEndorser;
import com.oocl.euc.core.maintenance.model.Users;
import com.oocl.euc.core.maintenance.repository.TeamEndorserRepository;
import com.oocl.euc.core.maintenance.repository.TeamRepository;
import com.oocl.euc.core.maintenance.repository.UsersRepository;
import com.oocl.euc.core.maintenance.vo.TeamEndorserVO;
import com.oocl.euc.framework.base.persistence.IBaseRepository;
import com.oocl.euc.framework.base.service.BaseService;
import com.oocl.euc.framework.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeamEndorserService extends BaseService<TeamEndorser, Long> {
    @Autowired
    TeamEndorserRepository teamEndorserRepository;

    @Autowired
    TeamService teamService;

    @Autowired
    TeamRepository teamRepository;

    @Autowired
    UsersRepository usersRepository;

    @Override
    protected IBaseRepository<TeamEndorser, Long> getRepository() {
        return teamEndorserRepository;
    }

    protected TeamService getTeamService(){
        return teamService;
    }

    protected  TeamRepository getTeamRepository(){
        return teamRepository;
    }

    protected  UsersRepository getUsersRepository() {
        return usersRepository;
    }

    protected  TeamEndorserRepository getTeamEndorserRepository() {
        return teamEndorserRepository;
    }

    public List<TeamEndorserVO> findDisplayName(Long teamId) {
        Team team = teamService.findOne(teamId);
        List<TeamEndorser> teamEndorsers = team.getTeamEndorsers();
        return teamEndorsers.stream().map(endorser -> new TeamEndorserVO(endorser.getUsers().getDomainId(), endorser.getUsers().getDisplayName()))
                .collect(Collectors.toList());
    }

    public TeamEndorser addTeamEndorserByTeamNameAndEndorser(String teamName, String endorser) {
        TeamEndorser teamEndorser = new TeamEndorser();
        teamEndorser.setEndorser(endorser);
        Team team = teamRepository.findByName(teamName).get(0);
        Users user = usersRepository.findByDomainId(endorser);
        if(user == null){
            throw new CustomException("Can not find this user.");
        }
        teamEndorser.setUsers(user);
        teamEndorser = teamEndorserRepository.save(teamEndorser);
        team.getTeamEndorsers().add(teamEndorser);
        teamRepository.save(team);
        return teamEndorser;
    }
}
